<?php

namespace App\Http\Controllers\Business;



use App\Events\Event;
use App\Events\ScheduleEvent;
use App\Model\Business\Classe;
use App\Model\Business\ClasseStuden;
use App\Model\Business\ScheduleStuden;
use App\Model\Eeoapi\Eeocourse;
use App\Model\Eeoapi\Eeosync;
use App\Model\Foundation\Student;
use App\Model\Foundation\Teacher;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Model\System\Token;
use Laravel\Lumen\Routing\Controller as BaseController;


use App\Model\Business\Schedule;
use App\Http\Controllers\MessagePacket;


/**
 *
 * 处理排课，支持约课，班课
 * Class ScheduleController
 * @version 0.1
 * @package App\Http\Controllers\Business
 */
class  LessonController extends BaseController
{
    use MessagePacket;


    private $courseType;

    function __construct()
    {
        $this->courseType = Schedule::LESSON;
    }


    /**
     * 获取单一排课的信息
     * @param $id
     * @return packetMessage
     */
    function getLesson($id)
    {
        $id = intval($id);
        $schedule = Schedule::find($id);
        $schedule->castinfo = array(
            "live"=>$schedule->live,
            "record"=>$schedule->record,
            "replay"=>$schedule->replay,
        );
        unset($schedule->live,$schedule->record,$schedule->replay);
        ## 获取课节回放视频
        $videosite = [];
        $result = DB::table('schedules_videos')
                ->select('videosite')
                ->where('scheduleid',$schedule->scheduleid)
                ->get();
        foreach ($result as $k=>$v) {
                $videosite[] = $v->videosite;
        }
        $schedule->videosite = $videosite;
        if(empty($schedule)){
            return $this->fail($schedule, '数据不存在');
        }
        return $this->success($schedule);
    }


    /**
     * 批量查询排课
     * @param Request $request
     * @return packetMessage
     */
    function getLessons(Request $request)
    {
        $schedule = Schedule::where('type', Schedule::LESSON);

        if($request->has('classeid')) {
            $tuid = intval($request->get('classeid'));
            $schedule->where('classeid',  $tuid);
        }
        if($request->has('begintime')){
            $schedule->where('begintime', '>=', $request->get('begintime'));
        }
        if($request->has('endtime')){
            $schedule->where('endtime', '<', $request->get('endtime'));
        }
        $schedules = $schedule->get();

        # 整合教师信息

            $teachers = [];
            foreach($schedules as $k=>$sche){
                $tinfo = [];
                if(!key_exists($sche->teacheruid, $teachers)){
                    $teachers[$sche->teacheruid] = Teacher::find($sche->teacheruid);
                }
                $tinfo['id'] = $sche->teacheruid;
                $tinfo['mobile'] = $teachers[$sche->teacheruid]->mobile;
                $tinfo['ClassInNo'] = $teachers[$sche->teacheruid]->ClassInNo;
                $tinfo['name'] = $teachers[$sche->teacheruid]->lastname;
                $tinfo['avatar'] = $teachers[$sche->teacheruid]->photo;
                $sche['teacherinfo'] = $tinfo;
                $sche['students'] = ScheduleStuden::getStudentByScheduleID($sche->scheduleid,1);
                $schedules[$k] = $sche;
            }

            foreach ($schedules as $schedule){
                $schedule->castinfo = array(
                    "live"=>$schedule->live,
                    "record"=>$schedule->record,
                    "replay"=>$schedule->replay,
                );
                unset($schedule->live,$schedule->record,$schedule->replay);
            ## 获取课节回放视频
            $videosite = [];
            $result = DB::table('schedules_videos')
                ->select('videosite')
                ->where('scheduleid',$schedule->scheduleid)
                ->get();
            foreach ($result as $k=>$v) {
                $videosite[] = $v->videosite;
            }
            $schedule->videosite = $videosite;
        }
        if(empty($schedules)){
            return $this->fail($schedules, '数据不存在');
        }
        return $this->success($schedules);
    }


    /**
     * 添加一个排课
     * @param Request $request
     * @return packetMessage
     */
    function  addLesson(Request $request)
    {
        try {
            if($request->has('lessons')){
                $lessons = $request->get('lessons');
            }else{
                return $this->fail(false, '缺少课节信息');
            }
            if(empty($lessons[0])){
                return $this->fail(false, '缺少课节信息');
            }

            # 获取班级信息
            $scheduleids = [];
            $classe = Classe::find($lessons[0]['classeid']);
            foreach ($lessons as $lesson) {
                if(key_exists('castinfo',$lesson)){
                    $castInfo = $lesson['castinfo'];
                    unset($lesson['castinfo']);
                    foreach ($castInfo as $k=>$v){
                        $lesson[$k] = $v;
                    }
                }
                $lesson['type'] = Schedule::LESSON;
                $lesson['coursetypeid'] = $classe->coursetypeid;
                $lesson['coursetypename'] = $classe->coursetypename;
                $lesson['quotas'] = $classe->quotas;
                $schedule = new Schedule($lesson);
                $schedule->created_by = Token::user()->userid;
                $schedule->updated_by = Token::user()->userid;
                $schedule->save();
                $scheduleids[] = $schedule->scheculeid;

                $students = ClasseStuden::where('classeid', $schedule->classeid)->get();
                foreach ($students as $student){
                    $obj = new ScheduleStuden();
                    $obj->scheduleid = $schedule->scheduleid;
                    $obj->studentuid = $student->studentuid;
                    $obj->identity = $student->identity;
                    $obj->save();
                }
                $schedule->usequotas = count($students);
                if($schedule->usequotas>=1){
                    $schedule->valide();
                }else{
                    $schedule->unvalide();
                }
                $schedule->save();
		        try{
                    #抛出创建事件
                    $this->dispatchScheduleEvent($schedule, Event::CREATE);
                }catch (\Exception $e){
                    $schedule->delete();
                    ScheduleStuden::whereIn('scheduleid', $schedule->scheduleid)->delete();
                    throw $e;
                }
            }
            return $this->success(true);
        }catch (\Exception $e){
            return $this->fail(false, '创建课节失败：'.$e->getMessage());
        }
    }


    /**
     * 更新某个排课的信息
     * @param Request $request
     * @return packetMessage
     */
    function  updateLesson(Request $request, $id=null)
    {

        try{
            # 兼容旧模式
            if(!$id){
                $id = $request->get('lessonuid');
            }
            $schedule = Schedule::find($id);

            $fields = $request->all();

            if(key_exists('castinfo',$fields)){
                $castInfo = $fields['castinfo'];
                unset($fields['castinfo']);
                foreach ($castInfo as $k=>$v){
                    $fields[$k] = $v;
                }
                foreach ($fields as $key=>$value){
                    $schedule->$key = $value;
                }

                $this->dispatchScheduleEvent($schedule, Event::LIVE);

                $schedule->updated_by = Token::user()->userid;

                $schedule->update($fields);

                return $this->success($schedule);
            }else{
                if($schedule->begintime < date('Y-m-d H:i:s')){
                    return $this->fail(false, '修改失败，该课节正在上课中或已结束');
                }
            }

            if($request->has('begintime') && $fields['begintime'] < date('Y-m-d H:i:s',time()+60)){
                return $this->fail(false, '修改失败，开课时间至少一分钟以后');
            }

            foreach ($fields as $key=>$value){
                $schedule->$key = $value;
            }

            $this->dispatchScheduleEvent($schedule, Event::UPDATE);

            $schedule->updated_by = Token::user()->userid;

            $schedule->update($fields);

            return $this->success($schedule);
        }catch (\Exception $e){
            return $this->fail(false, '修改课节失败,'.$e->getMessage());
        }
    }


    /**
     * 删除某个时间
     * @param $id
     * @return packetMessage
     */
    function  deleteLesson($id)
    {
        try{
            $obj = Schedule::find($id);
            $this->dispatchScheduleEvent($obj, Event::DELETE);

            Schedule::destroy($id);
            ScheduleStuden::where('scheduleid', $id)->delete();
            return $this->success(true);
        }catch (\Exception $e){
            return $this->fail(false, "删除失败：".$e->getMessage());
        }
    }


    /**
     * 获取课节学生
     * @param Request $request
     * @param $id
     * @return packetMessage
     */
    function getLessonStudents(Request $request, $id)
    {
        $id = intval($id);
        $relations = ScheduleStuden::where('scheduleid', $id)->where('identity',1)->get();
        if(empty($relations)){
            return $this->fail([], '没有数据');
        }
        $ids = [];
        foreach($relations as $k=>$val){
            $ids[] = $val['studentuid'];
        }
        $students = Student::wherein('studentuid', $ids)->get();

        foreach ($students as $student){
            $classinNo = Student::where('studentuid',$student->studentuid)->value('ClassInNo');
            $student->eeosync = Eeosync::where('scheduleid',$id)
                ->where('userid',$classinNo)
                ->where('type',Eeosync::STUDENT)->first();
        }

        return $this->success($students);
    }


    /**
     * 设置课节学生
     * @param Request $request
     * @param $id
     * @return array
     * @throws \Exception
     */
    function setLessonStudents(Request $request, $id)
    {
        try{
            if(!$request->has('students') and !$request->has('length')){
                return $this->fail(false, '缺少学生数据');
            }else{
                if($request->has('students')){
                    $students = $request->get('students');
                }else{
                    $students = [];
                }
            }

            $schedule = Schedule::find($id);
            $schedule->usequotas = count($students);
            if($schedule->usequotas>=1){
                $schedule->valide();
            }else{
                $schedule->unvalide();
            }
            $schedule->save();

            # 抛出事件
            $this->dispatchScheduleEvent($schedule, Event::STUDENT, $students);

            # 更新学生
            ScheduleStuden::where('scheduleid', $id)->delete();
            foreach($students as $student){
                $sst = new ScheduleStuden();
                $sst->scheduleid = $id;
                $sst->studentuid = $student;
                $sst->save();
            }
            return $this->success(true);
        }catch (\Exception $e){
            return $this->fail(false, "添加课节下学生失败：".$e->getMessage());
        }
    }


    /**
     * 抛出事件
     * @param $action
     * @param $obj
     * @return mixed
     * @throws \Exception
     */
    protected function dispatchScheduleEvent($obj, $action, $studentids=null)
    {
        try{
            $event = new ScheduleEvent($obj, $action);

            # 设置 eeo course id
            $eeocourse = Eeocourse::where('type', $this->courseType)
                ->where('chimpid', $obj->classeid)->first();
            if($eeocourse){
                $event->setCourseID($eeocourse->eeocourseid);
            }else{
                throw new \Exception('获取EEO Course ID 失败');
            }

            # 设置学生
            if($action == Event::STUDENT){
                $students = Student::wherein('studentuid', $studentids)->get();
                $event->setStudents($students);
                $oldStudents = ScheduleStuden::getStudentByScheduleID($obj->scheduleid);
                $event->setStudents($oldStudents, true);
            }

            # 设置直播参数

            event($event);
        }catch (\Exception $e){
            throw $e;
        }
    }

}
